import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// 加入 script setup 语法组件命名支持
import SetupExtend from 'unplugin-vue-setup-extend/vite'
import path from 'path'
// 动态导入 ElementPlus
// 先安装两个插件 npm install -D unplugin-vue-components unplugin-auto-import
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
// 解决 node.js 内置模块不能用问题
// 让 vite 支持引入 node 内置模块
// 先安装 npm i @esbuild-plugins/node-globals-polyfill @esbuild-plugins/node-modules-polyfill -D
import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'
import { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    AutoImport({ resolvers: [ElementPlusResolver()] }),
    Components({ resolvers: [ElementPlusResolver()] }),
    SetupExtend(),
  ],
  // base: './',
  resolve: {
    // 配置路径别名
    alias: {
      '@': path.resolve(__dirname, './src'),
      '@milkcan': path.resolve(__dirname, 'src/script/milkcan'),
      // 'vue': 'vue/dist/vue.esm-bundler.js',
      'util': 'rollup-plugin-node-polyfills/polyfills/util',
      'events': 'rollup-plugin-node-polyfills/polyfills/events',
      'stream': 'rollup-plugin-node-polyfills/polyfills/stream',
      'string_decoder': 'rollup-plugin-node-polyfills/polyfills/string-decoder',
      'zlib': 'rollup-plugin-node-polyfills/polyfills/zlib',
      'buffer': 'rollup-plugin-node-polyfills/polyfills/buffer-es6',
      'process': 'rollup-plugin-node-polyfills/polyfills/process-es6',
    },
  },
  optimizeDeps: {
    esbuildOptions: {
      // Node.js global to browser globalThis
      define: {
        global: 'globalThis'
      },
      // Enable esbuild polyfill plugins
      plugins: [
        NodeGlobalsPolyfillPlugin({  process: true, buffer: true  }),
        NodeModulesPolyfillPlugin()
      ]
    }
  },
  server: {
    host: '0.0.0.0',
    // open: true,
    hmr: true,
  }
})
